<?php

namespace App\Exception\Handler;

use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

/**
 * 重写
 */
class ValidationExceptionHandler extends \Hyperf\Validation\ValidationExceptionHandler
{

    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {

        /** @var ValidationException $throwable */
        $body = $throwable->validator->errors()->first();

        $data = [
            'code' => 500,
            'msg' => $body,
        ];

        return $response->withStatus(500)->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new \Hyperf\HttpMessage\Stream\SwooleStream(json_encode($data)));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}